/*
 * \brief  The first user process of the Genode process tree
 * \author Norman Feske
 * \date   2006-07-06
 */

/*
 * Copyright (C) 2006-2009 Norman Feske
 * Genode Labs, Feske & Helmuth Systementwicklung GbR
 *
 * This file is part of the Genode OS framework, which is distributed
 * under the terms of the GNU General Public License version 2.
 */

#include <base/env.h>
#include <base/sleep.h>
#include <cap_session/connection.h>
#include <rom_session/connection.h>
#include <init/nest.h>

using namespace Genode;
using namespace Init;


/**
 * Read and process configuration file
 */
static void process_config(Nest *children)
{
	/* request config file from ROM service */
	Rom_connection rom("config");
	rom.on_destruction(Rom_connection::KEEP_OPEN);
	void *addr = env()->rm_session()->attach(rom.dataspace());

	/*
	 * The XML data of a valid config file starts with
	 * a <config> tag.
	 */
	Xml_node config_node((const char *)addr);

	if (!config_node.is_type("config")) {
		printf("Error: Root node of config file is not a <config> tag.\n");
		return;
	}

	/*
	 * Iterate through all entries of the config file and start
	 * children as specified.
	 */
	for (int i = 0; i < config_node.num_sub_nodes(); i++) {
		Xml_node start_node = config_node.sub_node(i);
		if (start_node.is_type("start"))

			/* start child process */
			children->add_child(start_node);
		else {
			char buf[32];
			start_node.type_name(buf, sizeof(buf));
			printf("Warning: Ignoring unsupported tag <%s>.\n", buf);
		}
	}
}


int main(int argc, char **argv)
{
	printf("our quota limit is %zd\n", env()->ram_session()->quota());
	printf("our used quota is  %zd\n", env()->ram_session()->used());

	/* session to CAP service used to produce parent capabilities */
	static Cap_connection cap;

	/* container for holding Init's children */
	static Nest children(&cap);

	try {
		process_config(&children);
	} catch (Rom_file_missing) {
		printf("Error: No config file found.\n");
	} catch (Xml_node::Invalid_syntax) {
		printf("Error: Config file has invalid XML syntax.\n");
	}

	sleep_forever();
	return 0;
}
